package com.cpit.platform.web.controller;

import com.cpit.platform.dao.MainItemRepository;
import com.cpit.platform.dao.RoleRepository;
import com.cpit.platform.dao.UserToRoleRepository;
import com.cpit.platform.dto.*;
import com.cpit.platform.log.LogOperator;
import com.cpit.platform.security.service.UserInfo;
import com.cpit.platform.service.AuthorityService;
import com.cpit.platform.service.UserService;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

@Controller
@RequestMapping(value = "/system")
public class SystemController {

    @Autowired
    private MainItemRepository mItemRep = null;
    private final String loggerName = this.getClass().getName();
    @Autowired
    private UserService userService;
    @Autowired
    private UserToRoleRepository userToRoleRepository;
    @Autowired
    private RoleRepository roleRepository;

    @ApiOperation(value = "获取页面信息", notes = "通过条件查询获取系统页面信息，以实现Ajax局部刷新")
    @RequestMapping(value = "/ajaxRequestHTML/{thymeleafHtmlName}/{subfragment}", method = RequestMethod.GET)
    public String subsystem(
            @ApiParam(value = "页面名称，用－分割的文件夹和html文件名称。") @PathVariable String thymeleafHtmlName,
            @ApiParam(value = "子分块名称。") @PathVariable String subfragment,
            @RequestHeader("X-Requested-With") String requestedWith, HttpServletRequest request, Model model) {

        String SUB_VIEW_NAME = thymeleafHtmlName.replace("-", "/");

        String url = request.getParameter("url");
        model.addAttribute("url", url);
        model.addAttribute("none", "none");

//		if (AjaxUtil.isAjaxRequest(requestedWith)) {
        return SUB_VIEW_NAME.concat(" :: " + subfragment);
//		}
//		return SUB_VIEW_NAME;
    }

    @ApiOperation(value = "获取一级导航栏信息", notes = "动态获取一级导航栏信息，用于动态拼装导航栏页面结构。")
    @RequestMapping(value = "/getFirstNavItems", method = RequestMethod.GET)
    @ResponseBody
    public List<MainItem> getFirstNavItems() {
        List<MainItem> allMI = mItemRep.findAll();
        List<MainItem> ret = new ArrayList<MainItem>();
        if (allMI == null || allMI.size() == 0) {
            LogOperator.warn(loggerName, "no items in db");
            return ret;
        }
        // add groups
        for (MainItem i : allMI) {
            if (i.getType() == MainItem.ITEM_TYPE_ITEM) {
                continue;
            }
            ret.add(i);
        }
        // add sub items
        for (MainItem i : allMI) {
            if (i.getType() == MainItem.ITEM_TYPE_GROUP) {
                continue;
            }
            for (MainItem hash : ret) {
                if (hash.getId().equals(i.getParent())) {
                    // add to this group
                    hash.getChildren().add(i);
                }
            }
        }
        LogOperator.debug(loggerName, "all first level items:\n" + ret);
        return ret;
    }

    @ApiOperation(value = "获取导航栏信息", notes = "动态获取导航栏信息，用于动态拼装导航栏页面结构。")
    @RequestMapping(value = "/getNavItems", method = RequestMethod.GET)
    @ResponseBody
    public List<MainItem> getNavItems() {
        User user= userService.findByUsername(((UserInfo) SecurityContextHolder.getContext()
                .getAuthentication().getPrincipal()).getUsername());
        List<UserToRole> allRoles = userToRoleRepository.findByUserId(user.getId());

        List<Authority> authorityList=new ArrayList<Authority>();
        if(allRoles != null && allRoles.size() > 0) {
            for(UserToRole rr : allRoles) {
                Role r = roleRepository.findById(rr.getRoleId());
                List<Authority> allAuths = r.getAuthorities();
                if(allAuths != null && allAuths.size() > 0) {
                    authorityList.addAll(allAuths);
                }
            }
        }

        List<MainItem> allMI = mItemRep.findAll();
        List<MainItem> ret = new ArrayList<MainItem>();
        if (allMI == null || allMI.size() == 0) {
            LogOperator.warn(loggerName, "no items in db");
            return ret;
        }
        // add groups
        for (MainItem i : allMI) {
            if (i.getType() == MainItem.ITEM_TYPE_ITEM) {
                continue;
            }
            if (hasAuthority(authorityList,i.getAuthority())) {
                ret.add(i);
            }
        }
        // add sub items
        for (MainItem i : allMI) {
            if (i.getType() == MainItem.ITEM_TYPE_GROUP) {
                continue;
            }
            for (MainItem hash : ret) {
                if (hash.getId().equals(i.getParent())) {
                    // add to this group
                    if (hasAuthority(authorityList,i.getAuthority())) {
                        hash.getChildren().add(i);
                    }
                }
            }
        }
        LogOperator.debug(loggerName, "all first level items:\n" + ret);
        return ret;
    }

    private boolean hasAuthority(List<Authority> authorityList,String authority) {
        if (authorityList == null ||authorityList.size()==0) {
            return false;
        }

        LogOperator.warn(loggerName, "authority:"+authority);
        for (Authority a:authorityList){
            if (authority.indexOf(a.getAuthorityContent()) != -1) {
                return true;
            }
        }
        return false;
    }
}
